﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.ShopCart;

namespace NetCoreCMS.Web.Controllers
{
    public class View_AjaxController : Controller
    {
        public IArticleService _article { get; set; }
        public IArticle_commentService _article_comment { get; set; }
        public async Task<IActionResult> Index()
        {
            //取得处事类型
            string action = Request.Query["action"];
            ContentResult result = Content("SubmitAPI");
            switch (action)
            {
                case "view_article_click": //统计及输出阅读次数
                    result = await view_article_click();
                    break;
                case "view_comment_count": //输出评论总数
                    result = view_comment_count();
                    break;                             
            }
            return result;
        }
        #region 统计及输出阅读次数OK===========================
        private async Task<ContentResult> view_article_click()
        {
            int article_id = CMSRequest.GetQueryInt("id", 0, HttpContext);
            int click = CMSRequest.GetQueryInt("click", 0, HttpContext);
            int hide = CMSRequest.GetQueryInt("hide", 0, HttpContext);
            int count = 0;
            if (article_id > 0)
            {
                var model = await _article.GetClick(article_id);
                count = model.click;
                if (click > 0)
                {
                    _article.UpdateField(article_id, "click=click+1");
                }
            }
            if (hide == 0)
            {
                return Content("document.write('" + count + "');");
            }
            return Content("document.write('" + count + "');");
        }
        #endregion

        #region 输出评论总数OK=================================
        private ContentResult view_comment_count()
        {
            int article_id = 0;
            int.TryParse(Request.Query["id"], out article_id);
            int count = 0;
            if (article_id > 0)
            {
                count = _article_comment.RecordCount("where is_lock=0 and id>0 and article_id=" + article_id);
            }
            return Content("document.write('" + count + "');");
        }
        #endregion
        
    }
}